const App = {
  data() {
    return {
      loading: true,
      marketLoading: false, // 市场动态图表loading状态
      occupancyLoading: false, // 入住率图表loading状态
      top: {},
      marketChartInstance: null, // 市场动态图表实例
      bookingChartInstance: null, // 预订趋势图表实例
      roomTypeChartInstance: null, // 房型偏好图表实例
      durationChartInstance: null, // 入住时长分布图表实例
      sclabels: [],
      scdatasets: [
        {
          label: "预订量",
          data: [85, 92, 78, 105, 120, 115, 128],
          backgroundColor: "rgba(59, 130, 246, 0.1)",
          borderColor: "rgba(59, 130, 246, 1)",
          borderWidth: 2,
          tension: 0.3,
          fill: true,
        },
      ],
      ydlabels: ["1月", "2月", "3月", "4月", "5月", "6月", "7月"],
      yddatasets: [
        {
          label: "入住率",
          data: [65, 68, 70, 72, 75, 76, 78],
          backgroundColor: "rgba(16, 185, 129, 0.1)",
          borderColor: "rgba(16, 185, 129, 1)",
          borderWidth: 2,
          tension: 0.3,
          fill: true,
        },
      ],
      fxlabels: ["标准间", "大床房", "家庭房", "套房"],
      fxdatasets: [
        {
          data: [35, 40, 15, 10],
          backgroundColor: [
            "rgba(59, 130, 246, 0.8)",
            "rgba(16, 185, 129, 0.8)",
            "rgba(245, 158, 11, 0.8)",
            "rgba(124, 58, 237, 0.8)",
          ],
          borderWidth: 0,
        },
      ],
      rzlabels: ["1晚", "2晚", "3晚", "4晚", "5晚+"],
      rzdatasets: [
        {
          label: "入住时长",
          data: [25, 40, 20, 10, 5],
          backgroundColor: "rgba(59, 130, 246, 0.6)",
          borderColor: "rgba(59, 130, 246, 1)",
          borderWidth: 1,
        },
      ],
      selectedOption: "今日",
      options: [
        { value: "今日", text: "今日" },
        { value: "本周", text: "本周" },
        { value: "本月", text: "本月", selected: true },
        { value: "全年", text: "全年" },
        // { value: "自定义", text: "自定义" } // 注释掉的选项
      ],
      occupancyChartType: "week", // 默认选中 '日'
      bazaarChartType: "week", // 默认选中 '日'
      chartTypes: [
        // { type: "day", label: "日" },
        { type: "week", label: "周" },
        { type: "month", label: "月" },
      ],
      styleConfig: [
        {
          min: 0,
          max: 2,
          bg: "bg-gray-100",
          text: "text-gray-400",
          bold: false,
        }, // 低预订量
        {
          min: 3,
          max: 5,
          bg: "bg-blue-100",
          text: "text-blue-600",
          bold: false,
        }, // 中低
        {
          min: 6,
          max: 8,
          bg: "bg-blue-200",
          text: "text-blue-700",
          bold: false,
        }, // 中
        {
          min: 9,
          max: 11,
          bg: "bg-blue-300",
          text: "text-blue-800",
          bold: true,
        }, // 中高
        { min: 12, max: 99, bg: "bg-blue-400", text: "text-white", bold: true }, // 高预订量
      ],
      // 2. 修改：days数组新增「dailyBooking（每日入住量，即判断指标）」，移除写死的样式
      days: [],
    };
  },
  mounted() {
    this.loading = true;
    this.marketLoading = true;
    this.occupancyLoading = true;
    this.top3(); //三个指标
    this.marketDynamic(); //市场动态
    this.bookingTrend(); //预定趋势
    this.roomTypePreference(); //房型偏好
    this.checkInDuration(); //入住时长分布
    this.popularCheckInDate(); //热门入住日期
  },
  methods: {
    // 市场动态
    initBookingChart() {
      const bookingCtx = document
        .getElementById("bookingChart")
        .getContext("2d");
      // 1. 如果已有 Chart 实例，先销毁（避免重复渲染）
      if (this.marketChartInstance) {
        this.marketChartInstance.destroy();
      }
      this.marketChartInstance = new Chart(bookingCtx, {
        type: "line",
        data: {
          labels: this.sclabels, // 使用data中的labels
          datasets: this.scdatasets, // 使用data中的datasets
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          plugins: {
            legend: {
              display: false,
            },
          },
          scales: {
            y: {
              beginAtZero: true,
              grid: {
                color: "rgba(0, 0, 0, 0.05)",
              },
            },
            x: {
              grid: {
                display: false,
              },
            },
          },
        },
      });
    },
    //预定趋势
    initoccupancyChart() {
      const occupancyCtx = document
        .getElementById("occupancyChart")
        .getContext("2d");
      // 1. 如果已有 Chart 实例，先销毁（避免重复渲染）
      if (this.bookingChartInstance) {
        this.bookingChartInstance.destroy();
      }
      this.bookingChartInstance = new Chart(occupancyCtx, {
        type: "line",
        data: {
          labels: this.ydlabels, // 使用data中的labels
          datasets: this.yddatasets, // 使用data中的datasets
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          plugins: {
            legend: {
              display: false,
            },
          },
          scales: {
            y: {
              beginAtZero: true,
              max: 100,
              // ticks: {
              //   callback: function (value) {
              //     return value + "%";
              //   },
              // },
              grid: {
                color: "rgba(0, 0, 0, 0.05)",
              },
            },
            x: {
              grid: {
                display: false,
              },
            },
          },
        },
      });
    },
    //房型偏好
    initroomTypeChart() {
      const roomTypeCtx = document
        .getElementById("roomTypeChart")
        .getContext("2d");
      // 1. 如果已有 Chart 实例，先销毁（避免重复渲染）
      if (this.roomTypeChartInstance) {
        this.roomTypeChartInstance.destroy();
      }
      this.roomTypeChartInstance = new Chart(roomTypeCtx, {
        type: "doughnut",
        data: {
          labels: this.fxlabels, // 使用data中的labels
          datasets: this.fxdatasets, // 使用data中的datasets
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          plugins: {
            legend: {
              position: "right",
            },
          },
        },
      });
    },
    // 入住时长分布
    initstayDurationChart() {
      const stayDurationCtx = document
        .getElementById("stayDurationChart")
        .getContext("2d");
      // 1. 如果已有 Chart 实例，先销毁（避免重复渲染）
      if (this.durationChartInstance) {
        this.durationChartInstance.destroy();
      }
      this.durationChartInstance = new Chart(stayDurationCtx, {
        type: "bar",
        data: {
          labels: this.rzlabels, // 使用data中的labels
          datasets: this.rzdatasets, // 使用data中的datasets
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          plugins: {
            legend: {
              display: false,
            },
          },
          scales: {
            y: {
              beginAtZero: true,
              grid: {
                color: "rgba(0, 0, 0, 0.05)",
              },
              // ticks: {
              //   callback: function (value) {
              //     return value + "%";
              //   },
              // },
            },
            x: {
              grid: {
                display: false,
              },
              ticks: {
                // 为原始标签（如 '1'）添加“晚”单位
                callback: function (value) {
                  return this.getLabelForValue(value) + " 晚";
                },
              },
            },
          },
        },
      });
    },
    //三个指标
    top3() {
      const _this = this;
      $.ajax({
        headers: requestHeaders(),
        url: `${mh}/requestForward/requestForward?RequestURL=${encodeURIComponent(
          `/admin/charts/top3`
        )}`,
        type: "get",
        dataType: "json",
        complete: function (XMLHttpRequest) {
          requestPretreatment(XMLHttpRequest);
        },
        success: function (res) {
          console.log(res);
          _this.top = res.data;
        },
      });
    },
    //市场动态
    marketDynamic(day) {
      this.marketLoading = true;
      console.log(day);
      const _this = this;
      $.ajax({
        headers: requestHeaders(),
        url: `${mh}/requestForward/requestForward?RequestURL=${encodeURIComponent(
          `/admin/charts/marketDynamic?type=${this.bazaarChartType || ""}`
        )}`,
        type: "get",
        dataType: "json",
        complete: function (XMLHttpRequest) {
          requestPretreatment(XMLHttpRequest);
        },
        success: function (res) {
          console.log(res);
          _this.marketLoading = false;
          _this.scdatasets[0].data = res.data.data;
          _this.sclabels = res.data.labels;
          _this.initBookingChart();
        },
        error: function () {
          _this.marketLoading = false;
        },
      });
    },
    //预定趋势
    bookingTrend() {
      this.occupancyLoading = true;
      const _this = this;
      $.ajax({
        headers: requestHeaders(),
        url: `${mh}/requestForward/requestForward?RequestURL=${encodeURIComponent(
          `/admin/charts/bookingTrend?type=${this.occupancyChartType || ""}`
        )}`,
        type: "get",
        dataType: "json",
        complete: function (XMLHttpRequest) {
          requestPretreatment(XMLHttpRequest);
        },
        success: function (res) {
          _this.occupancyLoading = false;
          _this.yddatasets[0].data = res.data.data;
          _this.ydlabels = res.data.labels;
          _this.initoccupancyChart();
        },
        error: function () {
          _this.occupancyLoading = false;
        },
      });
    },
    //房型偏好
    roomTypePreference() {
      const _this = this;
      $.ajax({
        headers: requestHeaders(),
        url: `${mh}/requestForward/requestForward?RequestURL=${encodeURIComponent(
          `/admin/charts/roomTypePreference`
        )}`,
        type: "get",
        dataType: "json",
        complete: function (XMLHttpRequest) {
          requestPretreatment(XMLHttpRequest);
        },
        success: function (res) {
          _this.fxdatasets[0].data = res.data.data;
          _this.fxlabels = res.data.labels;
          _this.initroomTypeChart();
        },
      });
    },
    //入住时长分布
    checkInDuration() {
      const _this = this;
      $.ajax({
        headers: requestHeaders(),
        url: `${mh}/requestForward/requestForward?RequestURL=${encodeURIComponent(
          `/admin/charts/checkInDurationDistribution`
        )}`,
        type: "get",
        dataType: "json",
        complete: function (XMLHttpRequest) {
          requestPretreatment(XMLHttpRequest);
        },
        success: function (res) {
          _this.rzdatasets[0].data = res.data.data;
          _this.rzlabels = res.data.labels; // 关键：用接口数据覆盖初始值
          _this.initstayDurationChart(); // 重新渲染图表
        },
      });
    },
    //热门入住日期
    popularCheckInDate() {
      const _this = this;
      $.ajax({
        headers: requestHeaders(),
        url: `${mh}/requestForward/requestForward?RequestURL=${encodeURIComponent(
          `/admin/charts/popularCheckInDate`
        )}`,
        type: "get",
        dataType: "json",
        complete: function (XMLHttpRequest) {
          requestPretreatment(XMLHttpRequest);
        },
        success: function (res) {
          console.log("API返回的完整数据:", res);

          if (res.data.days && res.data.days.length > 0) {
            // 由于API没有返回年月信息，使用当前日期来获取年月
            const currentDate = new Date();
            const finalYear = currentDate.getFullYear();
            const finalMonth = currentDate.getMonth() + 1; // getMonth()返回0-11，需要+1

            // 计算当月1号是星期几
            const finalFirstDayOfMonth = new Date(finalYear, finalMonth - 1, 1);
            const finalFirstDayWeek = finalFirstDayOfMonth.getDay();

            // console.log("使用当前日期获取年月信息:");
            // console.log("年份:", finalYear, "月份:", finalMonth);
            // console.log(
            //   `${finalYear}年${finalMonth}月1号是星期${finalFirstDayWeek}（0=周日,1=周一,2=周二,3=周三,4=周四,5=周五,6=周六）`
            // );
            // console.log("最终需要添加的空白占位符数量:", finalFirstDayWeek);

            // 处理日期数据，添加星期信息
            const daysWithWeekInfo = res.data.days.map((dayItem) => {
              // 使用已确定的年月信息，而不是dayItem中可能不存在的year/month
              const date = new Date(finalYear, finalMonth - 1, dayItem.day);
              const dayOfWeek = date.getDay();
              let weekDay;
              switch (dayOfWeek) {
                case 0:
                  weekDay = "周日";
                  break;
                case 1:
                  weekDay = "周一";
                  break;
                case 2:
                  weekDay = "周二";
                  break;
                case 3:
                  weekDay = "周三";
                  break;
                case 4:
                  weekDay = "周四";
                  break;
                case 5:
                  weekDay = "周五";
                  break;
                case 6:
                  weekDay = "周六";
                  break;
              }
              // console.log(
              //   `第${dayItem.day}天: ${finalYear}-${finalMonth}-${dayItem.day} 是 ${weekDay}`
              // );
              return {
                ...dayItem,
                weekDay,
                year: finalYear, // 添加年份信息
                month: finalMonth, // 添加月份信息
              };
            });

            // 在月份前添加空白占位符，使1号对应正确的星期列
            const emptyPlaceholders = [];
            console.log("开始添加空白占位符，数量:", finalFirstDayWeek);
            for (let i = 0; i < finalFirstDayWeek; i++) {
              emptyPlaceholders.push({
                day: "",
                dailyBooking: 0,
                isEmpty: true, // 标记为空白占位符
                weekDay: "",
              });
            }
            console.log("已添加空白占位符:", emptyPlaceholders.length, "个");

            // 合并空白占位符和实际日期数据
            _this.days = [...emptyPlaceholders, ...daysWithWeekInfo];
            console.log("最终的days数组:", _this.days);
            console.log("数组长度:", _this.days.length);
            console.log("第一行（前7个）:", _this.days.slice(0, 7));
          } else {
            _this.days = [];
          }
        },
      });
    },
    getDayStyle(bookingCount) {
      // 遍历样式配置，找到当前指标对应的样式
      return this.styleConfig.find((config) => {
        return bookingCount >= config.min && bookingCount <= config.max;
      });
    },
    //预定趋势切换
    changeOccupancyChartType(day) {
      this.occupancyChartType = day;
      this.bookingTrend();
    },
    //市场动态切换
    changebazaarChartType(day) {
      // console.log(day);
      this.bazaarChartType = day;
      this.marketDynamic(day);
    },
  },
};
const { createApp, ref } = Vue;
const app = createApp(App);
app.use(ElementPlus, { locale: zhCn });
//这种方式是引入全部图标，无需单个引入
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component);
}
app.component("yl-upload", ylUpload);
app.component("yl-cascader", ylCascader);
app.component("yl-select", ylSelect);
app.component("yl-text-editor", ylTextEditor);
const ElMessage = ElementPlus.ElMessage;
app.mount("#app");
